package com.samxcode.leetcode;

/**
 * Reverse digits of an integer.
 * Example1: x = 123, return 321 
 * Example2: x = -123, return -321
 * 
 * @author Sam
 *
 */
public class ReverseInteger {

    public static void main(String[] args) {
        System.out.println(reverse(Integer.MIN_VALUE));
    }


    public static int reverse(int x) {
        try {
            char[] c;
            int flag = 1; //positive value or negative value
            if (x < 0) {
                c = String.valueOf(x).substring(1).toCharArray();
                flag = -1;
            } else {
                c = String.valueOf(x).toCharArray();
            }
            char res[] = new char[c.length];
            for (int i = c.length - 1, j = 0; i >= 0; i--) {
                res[j++] = c[i];
            }
            Integer n = Integer.parseInt(String.valueOf(res));
            return flag * n;
        } catch (NumberFormatException e) {
            return 0;
        }
    }

}
